<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Laravel\Passport\HasApiTokens;
use Hash;

class User extends Authenticatable
{
    use SoftDeletes, Notifiable, HasApiTokens;

    use SoftDeletes, EntrustUserTrait {
        SoftDeletes::restore insteadof EntrustUserTrait;
        EntrustUserTrait::restore as entrustRestore;
    }

    protected $casts = [
        'username' => 'string',
        'password' => 'string',
        'name' => 'string',
        'department_id' => 'integer',
        'post_id' => 'integer',
        'mobile' => 'string',
        'address' => 'string'
    ];

    protected $fillable = [
        'username', 'password', 'name', 'department_id', 'post_id', 'mobile', 'address'
    ];

    protected $hidden = [
        'password', 'remember_token', 'department' , 'post' ,'updated_at' ,'deleted_at'
    ];

    protected $appends = [
        'department_name','post_name', 'role_name'
    ];

    public function getDepartmentNameAttribute()
    {
        return ($this->department ? $this->department->name : '');
    }

    public function getPostNameAttribute()
    {
        return ($this->post ? $this->post->name : '');
    }

    public function getRoleNameAttribute()
    {
        return ($this->roles ? $this->roles[0]->description : '');
    }

    public function findForPassport($username)
    {
        return static::where('username', $username)->first();
    }

    public function getNoPasswordAttribute()
    {
        return Hash::check(null, $this->password);
    }

    public function post()
    {
        return $this->belongsTo(Post::class);
    }

    public function department()
    {
        return $this->belongsTo(Departments::class);
    }

    public function year_score()
    {
        return $this->hasMany(UserScore::class, 'to_user_id', 'id');
    }
}
